package com.wstuo.itsm.cim.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.wstuo.common.exception.ApplicationException;
/**
 * 导入的Util
 * @author gs60
 *
 */
public class CIImportUtil {
	final static Logger LOGGER = Logger.getLogger(CIImportUtil.class);
	public final static String FILED_IDENTITY = "attrVals";
	public final static String FILED_IDENTITY_SEPARATOR = "'";
	
	/**
	 * 提取基础（默认）导入的字段；
	 * @param fields
	 * @param filePath
	 * @param separator
	 */
	public static List<String> getDefaultField(List<String> fields
			,final String filePath,final String separator) {
		
		return fields;
	}
	/**
	 * 转换字段名
	 * @param colName
	 * @param separator
	 * @return
	 */
	public static String[] resolveColName(final String[] colName,final String separator){
		int len = 0;
		if( colName != null && (len = colName.length) > 0){
			String[] temp = null;
			String[] result = new String[ len ]; 
			for (int i = 0; i < len; i++) {
				String col = colName[i];
				if( col != null && (temp = col.split(separator)).length > 1){
					result[i] = temp[1];
				}else{
					result[i] = colName[i];
				}
			}
			return result;
		}
		return colName;
	}
	
	/**
	 * 列头字段转成map
	 * @param columnHead
	 * @param array
	 * @return
	 * @throws ApplicationException
	 */
	public static Map<String, Object> array2Map(final String[] columnHead,final String[] array)
			throws ApplicationException{
		Map<String, Object> result = new HashMap<String,Object>();
		if(columnHead != null && array != null) {
			int size = columnHead.length;
			if(array.length != size){
				throw new ApplicationException("columnHead length data length not equals");
			}
			for (int i = 0; i < size; i++) {
				if(  array[i] != null && array[i].length() > 0 ){
					//如果是拓展字段，那么开头肯定是attrVals
					if( columnHead[i].startsWith(FILED_IDENTITY) ){
						//拓展字段存储的是map对象，所以需要进行一个转换
						Object object = result.get(FILED_IDENTITY);
						Map<String, String> temp = 
								object == null ? (new HashMap<String,String>()):(Map<String,String>)object;
							temp.put(expandColName(columnHead[i]),  array[i]);
						result.put(FILED_IDENTITY, temp);
					}else{//基础字段，直接put进去
						result.put(columnHead[i], array[i]);
					}
				}
			}
		}
		return result;
	}
	
	/**
	 * 根据拓展字段名字进行转换
	 * attrVals['eav_1450676949796']  -> eav_1450676949796
	 */
	private static String expandColName(String colName){
		int startIndex = 0,endIndex = 0;
		if( colName != null 
				&& (startIndex = colName.indexOf(FILED_IDENTITY_SEPARATOR)) > 0 
				&& (endIndex = colName.lastIndexOf(FILED_IDENTITY_SEPARATOR)) > startIndex ){
			return colName.substring(startIndex + 1, endIndex);
		}
		return colName;
	}
	
	/**
	 * 读取Properties文件
	 * @param filePath
	 * @return
	 */
	public static LinkedHashMap<String, String> readPropertiesFile(final String filePath) {
		LinkedHashMap<String, String> result = new LinkedHashMap<String, String>();
		OrderedProperties prop = new OrderedProperties();
		FileInputStream in = null;
		try {
			in = new FileInputStream(filePath);
			prop.load(in);
			for (Object key : prop.keySet()) {
				result.put((String)key, (String)prop.get(key));
			}
		} catch (Exception e) {
			LOGGER.error(e);
		} finally{
			if( in != null ){
				try { in.close(); } catch (IOException e) { LOGGER.error(e); }
			}
		}
		return result;
	}
	
	/**
	 * 移除数组中的空白元素
	 * @param src
	 * @return
	 */
	public static String[] removeEmptyString(String[] src){
		if( src != null && src.length > 0 ){
			List<String> result = new ArrayList<String>();
			for (String string : src) {
				if( string != null && string.length() > 0){
					result.add(string);
				}
			}
			return result.toArray(new String[result.size()]);
		}
		return src;
	}

}
